package com.icode50.spring.controller;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.icode50.spring.entity.User;
import com.icode50.spring.model.result.Result;
import com.icode50.spring.model.result.ResultFactory;
import com.icode50.spring.service.serviceImpl.UserServiceImpl;

import io.swagger.annotations.Api;

@Api
@RestController
@RequestMapping("/api")
public class LoginController {

    @Autowired
    private UserServiceImpl userService;

    @CrossOrigin//支持跨域
    @PostMapping("/login")
    @ResponseBody
    public Result login(@RequestBody User requestUser,HttpSession session){
        String userName = requestUser.getUserName();
        User user = userService.getUserByUserName(userName);
        System.out.println("UserName: " + requestUser.getUserName() + ", Password: " + requestUser.getPassword());
        if(null == user) {
            String message = "账号/密码错误！";
            System.out.println(message);
            return ResultFactory.bulidFailResult(message);
        } else {
            session.setAttribute("user",user);
            return ResultFactory.bulidSuccessResult(user);
        }
    }

    @CrossOrigin
    @PostMapping("/logout")
    @ResponseBody
    public Result logout(HttpSession httpSession){
        httpSession.removeAttribute("user");
        return ResultFactory.bulidSuccessResult("请重新登录");
    }

}
